<template>
  <a-modal :width="1200" v-model:visible="showCampaignDetail" :title="showTypeMap[showType].title" title-align="start" :mask-closable="false" :footer="false" @cancel="closedDialog">
    <template v-if="showType === 'campaign'">
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">店铺：</p>
            <p class="val">{{ currentData.shopName }}</p>
          </div>
        </a-col>
        <a-col :span="9">
          <div class="flex">
            <p class="label">广告活动：</p>
            <div>
              <p class="val">{{ currentData.campaignName }}</p>
              <p class="info">{{ currentData.campaignId }}</p>
            </div>
          </div>
        </a-col>
        <a-col :span="5">
          <div class="flex">
            <p class="label">预算：</p>
            <p class="val">{{ currentData.budgetAmount }}</p>
          </div>
        </a-col>
      </a-row>
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">状态：</p>
            <p class="val">{{ AdStatus[currentData.state] }}</p>
          </div>
        </a-col>
        <a-col :span="9">
          <div class="flex">
            <p class="label">组合名称：</p>
            <p class="val">{{ currentData.portfolioName }}</p>
          </div>
        </a-col>
        <a-col :span="5">
          <div class="flex">
            <p class="label">销售员：</p>
            <p class="val">{{ currentData.ownerName }}</p>
          </div>
        </a-col>
      </a-row>
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">类型：</p>
            <p class="val">{{ AdTypes[currentData.adType] }}</p>
          </div>
        </a-col>
        <a-col :span="9">
          <div class="flex">
            <p class="label">投放类型：</p>
            <p class="val">缺</p>
          </div>
        </a-col>
        <a-col :span="5">
          <div class="flex">
            <p class="label">竞价策略：</p>
            <p class="val">{{ DynamicBudgetStrategy[currentData.dynamicBudgetStrategy] || '未知' }}</p>
          </div>
        </a-col>
      </a-row>
    </template>
    <template v-if="showType === 'adGroup'">
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">广告组：</p>
            <p class="val">{{ currentData.adGroupName }}</p>
          </div>
        </a-col>
        <a-col :span="9">
          <div class="flex">
            <p class="label">广告活动：</p>
            <p class="val">{{ currentData.campaignName }}</p>
          </div>
        </a-col>
        <a-col :span="5">
          <div class="flex">
            <p class="label">竞价：</p>
            <p class="val">{{ currentData.defaultBid }}</p>
          </div>
        </a-col>
      </a-row>
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">状态：</p>
            <p class="val">{{ AdStatus[currentData.state] }}</p>
          </div>
        </a-col>
        <a-col :span="9">
          <div class="flex">
            <p class="label">店铺：</p>
            <p class="val">{{ currentData.shopName }}</p>
          </div>
        </a-col>
        <a-col :span="5">
          <div class="flex">
            <p class="label">广告类型：</p>
            <p class="val">{{ AdTypes[currentData.adType] }}</p>
          </div>
        </a-col>
      </a-row>
    </template>
    <template v-if="showType === 'searchTerm' || showType === 'keyword'">
      <a-row class="detail-item">
        <template v-if="showType === 'searchTerm'">
          <a-col :span="8">
            <div class="flex">
              <p class="label">搜索词：</p>
              <p class="val">{{ currentData.searchTerm }}</p>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex">
              <p class="label">投放目标：</p>
              <div>
                <p class="val">{{ currentData.targeting || '--' }}</p>
                <p class="info">{{ SearchTermTargetingObjType[currentData.targetingObjType] || currentData.targetingObjType }}</p>
              </div>
            </div>
          </a-col>
        </template>
        <template v-else>
          <a-col :span="8">
            <div class="flex">
              <p class="label">关键词：</p>
              <p class="val">{{ currentData.keywordText }}</p>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex">
              <p class="label">匹配类型：</p>
              <div>
                <p class="val">{{ KeywordMatchType[currentData.matchType] || currentData.matchType }}匹配</p>
              </div>
            </div>
          </a-col>
        </template>
        <a-col :span="8">
          <div class="flex">
            <p class="label">广告活动：</p>
            <p class="val">{{ currentData.campaignName }}</p>
          </div>
        </a-col>
      </a-row>
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">广告组：</p>
            <p class="val">{{ currentData.adGroupName }}</p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="flex">
            <p class="label">店铺：</p>
            <p class="val">{{ currentData.shopName }}</p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="flex">
            <p class="label">广告类型：</p>
            <p class="val">{{ AdTypes[currentData.adType] }}</p>
          </div>
        </a-col>
      </a-row>
    </template>
    <template v-if="showType === 'targeting'">
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">投放组：</p>
            <p class="val">{{ TargetingExpressionTypeMap[currentData.targetingExpressionType] || currentData.targetingExpressionType }}</p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="flex">
            <p class="label">店铺：</p>
            <p class="val">{{ currentData.shopName }}</p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="flex">
            <p class="label">广告组合：</p>
            <p class="val">{{ currentData.portfolioName }}</p>
          </div>
        </a-col>
      </a-row>
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">广告活动：</p>
            <p class="val">{{ currentData.campaignName }}</p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="flex">
            <p class="label">广告组：</p>
            <p class="val">{{ currentData.adGroupName }}</p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="flex">
            <p class="label">状态：</p>
            <div>
              <p class="val">{{ AdStatus[currentData.state] }}</p>
              <p class="info">{{ ServingStatusMap[currentData.servingStatus] || currentData.servingStatus }}</p>
            </div>
          </div>
        </a-col>
      </a-row>
    </template>
    <div class="search-w flex-c-sb">
      <div class="flex-c">
        <a-radio-group v-if="showType != 'searchTerm'" type="button" v-model="modelType" style="margin-right: 20px">
          <a-radio :value="1">趋势</a-radio>
          <a-radio :value="2">数据对比</a-radio>
        </a-radio-group>
        <a-range-picker v-model="timeVal" shortcuts-position="left" :shortcuts="rangeShortcuts()" style="width: 260px" @change="startSearch" />
      </div>
      <a-button size="mini" type="outline" @click="toExcel">导出</a-button>
    </div>
    <!-- 趋势 -->
    <div v-show="modelType == 1" class="detail-con-w">
      <!-- 图表 -->
      <AdChart ref="adChartRef" :type="showType" :searchParams="searchParam" :height="150" />
      <!-- table -->
      <a-table size="mini" :scroll="{ y: '100%' }" class="table-singe-line" :bordered="false" :pagination="false" :data="dateTableList">
        <template #columns>
          <a-table-column title="日期" :width="85" :sortable="sortable" data-index="reportDate" />
          <a-table-column v-if="showType === 'campaign'" title="每日预算" align="right" :width="80" data-index="budgetAmount">
            <template #cell="{ record }">
              <p>
                <span>{{ getCurrencySymbol() }}</span>
                <span>{{ record.budgetAmount }}</span>
              </p>
            </template>
          </a-table-column>
          <a-table-column v-if="showType === 'adGroup'" title="竞价" align="right" :width="80" data-index="defaultBid">
            <template #cell="{ record }">
              <p>
                <span>{{ getCurrencySymbol() }}</span>
                <span>{{ record.defaultBid }}</span>
              </p>
            </template>
          </a-table-column>
          <a-table-column v-for="(item, index) of columns" :key="index" align="right" :width="item.width" :title="item.title" :sortable="item.sortable" :data-index="item.dataIndex">
            <template v-if="['ctr', 'cvr', 'acos'].includes(item.dataIndex)" #cell="{ record }">
              <p v-if="record[item.dataIndex] || record[item.dataIndex] === 0">{{ Number(record[item.dataIndex]).toFixed(2) }}%</p>
              <p v-else>--</p>
            </template>
            <template v-else-if="['cost', 'cpc', 'cpa', 'saleAmount', 'roas'].includes(item.dataIndex)" #cell="{ record }">
              <p v-if="record[item.dataIndex] || record[item.dataIndex] === 0">
                <span v-if="item.dataIndex != 'roas'">$</span>
                <span>{{ Number(record[item.dataIndex]).toFixed(2) }}</span>
              </p>
              <p v-else>--</p>
            </template>
            <template v-else #cell="{ record }">
              <p>{{ record[item.dataIndex] }}</p>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
    <!-- 数据对比 -->
    <div v-show="modelType == 2" class="detail-con-w">
      <a-table style="margin-top: 10px" size="mini" class="table-singe-line" :scroll="{ y: '100%' }" :bordered="false" :pagination="false" :data="contrastTableList">
        <template #columns>
          <a-table-column title="日期" :width="160">
            <template #cell="{ record, rowIndex }">
              <p>{{ rowIndex === 1 ? '环比' : rowIndex === 2 ? '年同比' : '' }}</p>
              <p>{{ $setTime(record.startDate, 'YYYY/MM/DD') }}~{{ $setTime(record.endDate, 'YYYY/MM/DD') }}</p>
            </template>
          </a-table-column>

          <a-table-column v-for="(item, index) of columns" :key="index" align="right" :width="item.width" :title="item.title" :sortable="item.sortable" :data-index="item.dataIndex">
            <template v-if="['ctr', 'cvr', 'acos'].includes(item.dataIndex)" #cell="{ record }">
              <p v-if="record[item.dataIndex] || record[item.dataIndex] === 0">{{ Number(record[item.dataIndex]).toFixed(2) }}%</p>
              <p v-else>--</p>
            </template>
            <template v-else-if="['cost', 'cpc', 'cpa', 'saleAmount', 'roas'].includes(item.dataIndex)" #cell="{ record }">
              <p v-if="record[item.dataIndex] || record[item.dataIndex] === 0">
                <span v-if="item.dataIndex != 'roas'">$</span>
                <span>{{ Number(record[item.dataIndex]).toFixed(2) }}</span>
              </p>
              <p v-else>--</p>
            </template>
            <template v-else #cell="{ record }">
              <p>{{ record[item.dataIndex] }}</p>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, nextTick, onMounted } from 'vue'
  import { campaignTrendCharts, campaignDateRangeContrast, targetingTrendCharts, targetingContrast, searchTermTrendCharts, keywordpContrast, keywordTrendCharts, adGroupContrast, adGroupTrendCharts } from '@/api/advert'
  import { AdStatus, AdTypes, DynamicBudgetStrategy } from '../../types'
  import AdChart from './adChart.vue'
  import { rangeShortcuts } from '@/utils/timeFormat'
  import { marketPlaceList, currencySymbol } from '@/utils/globalData'
  import ExportExcel from '@/utils/exportExcel'
  import { SearchTermTargetingObjType, KeywordMatchType, TargetingExpressionTypeMap, ServingStatusMap } from '../../types'
  onMounted(() => {
    setDefaultSearchVal()
    startSearch()
  })
  const emit = defineEmits(['closed'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentData: {
      type: Object,
      default: () => {},
    },
    defaultSearchVal: {
      type: Object,
      default: () => {},
    },
    showType: {
      type: String,
      default: 'campaign', //campaign广告活动详情，adGroup广告组详情
    },
  })
  const sortable = {
    sortDirections: ['ascend', 'descend'],
  }
  const showTypeMap = {
    campaign: {
      title: '广告活动趋势分析',
      contrastApi: campaignDateRangeContrast,
      chartsApi: campaignTrendCharts,
    },
    adGroup: {
      title: '广告组趋势分析',
      contrastApi: adGroupContrast,
      chartsApi: adGroupTrendCharts,
    },
    keyword: {
      title: '关键词趋势分析',
      contrastApi: keywordpContrast,
      chartsApi: keywordTrendCharts,
    },
    searchTerm: {
      title: '搜索词趋势分析',
      chartsApi: searchTermTrendCharts,
    },
    targeting: {
      title: '自动投放趋势分析',
      contrastApi: targetingContrast,
      chartsApi: targetingTrendCharts,
    },
  }
  const columns = [
    {
      title: '曝光量',
      dataIndex: 'impressions',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '点击量',
      dataIndex: 'clicks',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'CTR',
      dataIndex: 'ctr',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '花费',
      dataIndex: 'cost',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'CPC',
      dataIndex: 'cpc',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'CVR',
      dataIndex: 'cvr',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'CPA',
      dataIndex: 'cpa',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '总单量',
      dataIndex: 'purchasesOrder',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '商品销量',
      dataIndex: 'purchasesSale',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: '销售额',
      dataIndex: 'saleAmount',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'ACOS',
      dataIndex: 'acos',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
    {
      title: 'ROAS',
      dataIndex: 'roas',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 80,
    },
  ]
  const showCampaignDetail = ref(props.isShow)
  const searchParam = ref<any>({
    shopId: props.currentData.shopId,
    adType: props.currentData.adType,
    isDetail: true,
    portfolioIds: props.currentData.portfolioId ? [props.currentData.portfolioId] : null,
  })
  const timeVal = ref<Array<string>>([props.defaultSearchVal.startDate, props.defaultSearchVal.endDate])
  const modelType = ref(1)
  const adChartRef = ref()
  const dateTableList = ref([])
  const contrastTableList = ref([])
  const tableLoading = ref(false)

  // 设置查询条件
  function setDefaultSearchVal() {
    if (props.showType == 'campaign') {
      searchParam.value.campaignId = props.currentData.campaignId
    } else if (props.showType == 'adGroup') {
      searchParam.value.campaignId = props.currentData.campaignId
      searchParam.value.adGroupId = props.currentData.adGroupId
    } else if (props.showType == 'keyword') {
      searchParam.value.campaignId = props.currentData.campaignId
      searchParam.value.adGroupId = props.currentData.adGroupId
      searchParam.value.keywordId = props.currentData.keywordId
    } else if (props.showType == 'searchTerm') {
      searchParam.value.campaignIds = props.currentData.campaignId ? [props.currentData.campaignId] : null
      searchParam.value.adGroupIds = props.currentData.adGroupId ? [props.currentData.adGroupId] : null
      searchParam.value.searchTerm = props.currentData.searchTerm
    } else if (props.showType == 'targeting') {
      searchParam.value.campaignIds = props.currentData.campaignId ? [props.currentData.campaignId] : null
      searchParam.value.adGroupIds = props.currentData.adGroupId ? [props.currentData.adGroupId] : null
      searchParam.value.targetId = props.currentData.targetId
      searchParam.value.targetIds = props.currentData.targetId ? [props.currentData.targetId] : null
    }
  }
  // 显示货币符号
  function getCurrencySymbol() {
    let currency = marketPlaceList[props.currentData.marketplaceId]?.currency
    return currencySymbol[currency]
  }
  // 设置初始化查询条件
  function startSearch() {
    searchParam.value.startDate = timeVal.value[0]
    searchParam.value.endDate = timeVal.value[1]
    nextTick(async () => {
      adChartRef.value.refreshData()
      tableLoading.value = true
      await getDateTableList()
      await getChainRelativeRatio()
      tableLoading.value = false
    })
  }
  // 获取趋势详细数据
  async function getDateTableList() {
    let apiRequest = showTypeMap[props.showType]?.chartsApi
    if (!apiRequest) return
    let res: any = await apiRequest(searchParam.value)
    dateTableList.value = res?.data || []
  }
  // 获取环比数据
  async function getChainRelativeRatio() {
    let apiRequest = showTypeMap[props.showType]?.contrastApi
    if (!apiRequest) return
    let res: any = await apiRequest(searchParam.value)
    contrastTableList.value = res?.data || []
  }
  // 导出
  function toExcel() {
    let fieldColumns = columns.map((el: any) => {
      return { key: el.dataIndex, name: el.title }
    })

    let excelDatas = dateTableList.value?.map((item) => {
      let _item = JSON.parse(JSON.stringify(item))
      Object.keys(_item).forEach((key: string) => {
        if (['budgetAmount', 'defaultBid'].includes(key)) {
          _item[key] = getCurrencySymbol() + _item[key]
        } else if (['ctr', 'cvr', 'acos'].includes(key)) {
          _item[key] = _item[key]?.toFixed(2) + '%'
        } else if (['cost', 'cpc', 'cpa', 'saleAmount', 'roas'].includes(key)) {
          _item[key] = _item[key]?.toFixed(2)
        }
      })
      return _item
    })
    if (props.showType === 'campaign') {
      let name = `广告活动${props.currentData?.campaignName}趋势分析`
      let excelColumns = [{ key: 'reportDate', name: '日期' }, { key: 'budgetAmount', name: '每日预算' }, ...fieldColumns]
      ExportExcel(excelColumns, excelDatas, name)
    } else {
      let name = `广告组${props.currentData?.adGroupName}趋势分析`
      let excelColumns = [{ key: 'reportDate', name: '日期' }, { key: 'defaultBid', name: '竞价' }, ...fieldColumns]
      ExportExcel(excelColumns, excelDatas, name)
    }
  }

  // 关闭
  function closedDialog() {
    showCampaignDetail.value = false
    emit('closed')
  }
</script>
<style lang="less" scoped>
  .detail-item {
    margin-bottom: 5px;
    height: 30px;
    line-height: 14px;
    .label {
      width: 80px;
      text-align: right;
    }
    .val {
      color: #666;
    }
    .info {
      font-size: 12px;
      color: #999;
    }
  }
  :deep(.arco-radio-group-button) {
    padding: 0;
    .arco-radio-button {
      margin: 0;
      background-color: #fff;
      line-height: 30px;
      border: 1px solid var(--color-border);
      &:first-child {
        border-radius: 5px 0 0 5px;
      }
      &:last-child {
        border-radius: 0 5px 5px 0;
      }
    }
    .arco-radio-checked {
      border-color: rgb(var(--primary-6));
    }
  }
  .detail-con-w {
    height: calc(90vh - 250px);
    overflow-y: hidden;
    display: flex;
    flex-direction: column;
    .arco-table {
      flex: 1;
      height: 100%;
      overflow-y: hidden;
    }
  }

  :deep(.arco-table-sorter) {
    margin-left: 2px;
  }
</style>
